package com.iot.manage.biz.controller;

import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import java.util.List;
import javax.validation.Valid;
import org.springframework.web.bind.annotation.*;
import com.iot.common.core.exception.ModelException;
import com.iot.common.core.util.R;
import com.iot.common.core.util.UuidUtil;
import com.iot.common.security.annotation.SecurityAuthorization;
import com.iot.manage.api.domain.SysDict;
import com.iot.manage.api.domain.SysDictItem;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;

@RestController
@RequiredArgsConstructor
@RequestMapping("/dict")
@Api(value = "dict", tags = "字典")
public class DictController {

	@Setter
	private Throwable cause;

	@SecurityAuthorization
	@GetMapping(value = { "/list" }, produces = "application/json; charset=utf-8")
	public R<List<SysDict>> list(@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "rootId", required = false, defaultValue = "-1") String rootId) throws Exception {
		List<SysDict> sysDict = SysDict.dao.find("SELECT T.*,(CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM "
				+ SysDict.TABLE_NAME + " WHERE PARENTID=T.ID)>0 THEN 1 ELSE  0 END )  as hasChildren FROM "
				+ SysDict.TABLE_NAME + " T WHERE T.PARENTID=? ORDER BY T.SORT ASC ", rootId);
		return R.ok(sysDict);
	}

	@SecurityAuthorization
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<SysDict> save(@Valid SysDict sysDict) {
		if (sysDict == null) {
			throw new ModelException("对象不可以为空！");
		}
		if (StrKit.isBlank(sysDict.getId())) {
			sysDict.setId(UuidUtil.getUUID());
			if (sysDict.save()) {
				return R.ok(sysDict);
			}
		} else {
			if (sysDict.update()) {
				return R.ok(sysDict);
			}
		}
		return R.failed();
	}

	@SecurityAuthorization
	@PostMapping(value = { "/deleteById" }, produces = "application/json; charset=utf-8")
	public R<Boolean> deleteById(@RequestParam(name = "id", required = true) String id) throws Exception {
		if (Db.queryDouble("SELECT COUNT(*) FROM " + SysDict.TABLE_NAME + " WHERE PARENTID=?", id) > 0) {
			return R.failed("有子节点，不允许删除！", false);
		}
		if (SysDict.dao.deleteById(id)) {
			Db.delete("delete from " + SysDictItem.TABLE_NAME + " where dictId=? ", id);
			return R.ok(true);
		} else {
			return R.failed(false);
		}
	}

	@SecurityAuthorization
	@GetMapping(value = { "/listForItems" }, produces = "application/json; charset=utf-8")
	public R<List<SysDictItem>> listForItems(
			@RequestParam(name = "dictId", required = false, defaultValue = "") String dictId) throws Exception {
		String sqlExceptSelect = " FROM " + SysDictItem.TABLE_NAME + " o  WHERE o.dictId='" + dictId + "' ";
		sqlExceptSelect += "  ORDER BY   O.sort asc ";
		return R.ok(SysDictItem.dao.find("select * " + sqlExceptSelect));
	}

	@SecurityAuthorization
	@RequestMapping(value = "/saveForItem", method = RequestMethod.POST)
	public R<SysDictItem> saveForItem(@Valid SysDictItem sysDictItem) {
		if (sysDictItem == null) {
			throw new ModelException("对象不可以为空！");
		}
		if (StrKit.isBlank(sysDictItem.getId())) {
			sysDictItem.setId(UuidUtil.getUUID());
			if (sysDictItem.save()) {
				return R.ok();
			}
		} else {
			if (sysDictItem.update()) {
				return R.ok();
			}
		}
		return R.failed();
	}

	@SecurityAuthorization
	@PostMapping(value = { "/deleteForItem" }, produces = "application/json; charset=utf-8")
	public R<Boolean> deleteForItem(@RequestParam(name = "id", required = true) String id) throws Exception {
		if (SysDictItem.dao.deleteById(id)) {
			return R.ok(true);
		} else {
			return R.failed(false);
		}
	}
	
	/**
	 * 获取字典项
	 * @param code
	 * @param keywords
	 * @return
	 */
	@SecurityAuthorization
	@PostMapping(value = { "/getItems" }, produces = "application/json; charset=utf-8")
	public R<List<SysDictItem>> getItems(@RequestParam(name = "code", required = true) String code,@RequestParam(name = "keywords", required = false) String keywords){
		String _sql="select label,value,code from "+SysDictItem.TABLE_NAME+" where dictId in (select id from  "+SysDict.TABLE_NAME+" where code='"+code+"' )";
		if(!StrKit.isBlank(keywords)) {
			_sql+=" and ( code like '%"+keywords+"%' and label like '%"+keywords+"%' ) ";
		}
		_sql+=" ORDER BY SORT ASC";
		return R.ok(SysDictItem.dao.find(_sql));
	}
	

}
